import { Models } from '../../../../common/typings/model'
import Config from '../../../../config/Config'
import KoaRouter from 'koa-router'
import Mysql from '../../../../core/Mysql'
import { Success } from '../../../../core/HttpException'
import validator from '../../../../middlewares/validator'
import Auth from '../../../../middlewares/Auth'
import addRole from '../../../../common/apiValidate/system/role/addRole'
import DateUtils from '../../../../common/utils/DateUtils'
import RedisClient from '../../../../core/Redis'

const router = new KoaRouter({
  prefix: `${Config.api_prefix}system/role`,
})

router.post('/add', Auth.verifyTokenPermission, validator(addRole, 'body'), async (ctx: Models.Ctx) => {
  const { name, parentId, describe = '', serialNum } = ctx.request.body
  const date = DateUtils.format(new Date())
  const res = await Mysql.command(`
    INSERT INTO role ( name, parent_id, \`describe\`, serial_num, created_at, updated_at )
    VALUES
    ( '${name}', ${parentId}, '${describe}', ${serialNum}, '${date}', '${date}' );
  `)
  // const scope = res.results.insertId
  // Auth.getUserPermission({
  //   scope,
  //   uid: ctx.auth.uid,
  // }).then((list) => {
  //   RedisClient.addRoles(
  //     scope,
  //     list.map((item) => item.permission)
  //   )
  // })
  //
  Auth.updateRedisRole()
  throw new Success(res)
})

export default router
